// 封装axios
/*
    1. 封装可以简化我们接口调用的代码，可以去掉一些重复的代码
    2. 换掉Axios也是比较简单的
    3. 
*/
import axios from 'axios'
import { CONFIG } from '../config/index.js'
import router from '../router/index.js'
import { ElMessage } from 'element-plus';

//请求拦截器
axios.interceptors.request.use(function (config){
    // console.log("请求拦截器",config)
    if (config.method == "get") {
        let timeStamp = (new Date()).getTime()
        // 打印时间
        // console.log("timeStamp:", timeStamp) 
        if (config.params){
            config.params.timeStamp = timeStamp
        }else{
            config.params = {
                timeStamp: timeStamp
            }
        }
    }

    //从windows的localStorage中取出Authorization即token的值
    let TokenValue = ""
    try {
        TokenValue = window.localStorage.getItem(CONFIG.TOKEN_NAME)
    }catch {error}{
        TokenValue = ""
    }
    if (TokenValue == "" || TokenValue == null){
        config.headers[CONFIG.TOKEN_NAME] = ""
    }else{
        config.headers[CONFIG.TOKEN_NAME] = TokenValue
    }

    return config;
}, function (error) {
    return Promise.reject(error);
});

//相应拦截器
axios.interceptors.response.use(function (response){
    // console.log("response:", response)
    if (response.data.status === 200){
        return Promise.resolve(response)
    }else  if (response.data.status === 401){
        //当显示为401错误时，证明token已经失效，显示提示弹窗
        ElMessage({
            type: "Warning",
            message :response.data.message
        })
        //删除失效token
        window.localStorage.removeItem(CONFIG.TOKEN_NAME)
        //取到当前访问路径,当访问路径为/login时无需跳转，反之则跳转到登录界面
        router.currentRoute.path != "/login" && router.replace("/login")
    }
    return response;
},function(error){
    ElMessage({
        type: "error",
        message: "请求错误: "+error.message
    })
    return Promise.reject(error);
})

const request = (url = '', data = {}, method = "get", timeout = 5000) => {
    // console.log("使用封装函数去处理请求")
    return new Promise((resolve, reject)=>{
    // console.log("使用axios请求接口")
        // GET POST 
        const methodLower = method.toLowerCase() 
        if (methodLower === 'get') {
            axios({
                method: methodLower,
                params: data,
                timeout: timeout,
                url: url,
            }).then((response)=>{
                // 能正常拿到数据
                resolve(response)
            }).catch((error)=>{
                reject(error)
            })
        } else if (methodLower === "post") {
            axios({
                method: methodLower,
                data: data,
                timeout: timeout,
                url: url,
            }).then((response)=>{
                // 能正常拿到数据
                resolve(response)
            }).catch((error)=>{
                reject(error)
            })
        }
    })
}

export default request